package com.zhang.bingmei_incomeexpenditure.service.chain.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhang.bingmei_incomeexpenditure.entity.ie.IncomeExpenditure;
import com.zhang.bingmei_incomeexpenditure.entity.ie.updateNew.UpdateDoubleDTO;
import com.zhang.bingmei_incomeexpenditure.mapper.IncomeExpenditureMapper;
import com.zhang.bingmei_incomeexpenditure.service.chain.ValidationHandler;

// 唯一性校验处理器
public class UniquenessValidationHandler implements ValidationHandler {
    private ValidationHandler next;
    private final IncomeExpenditureMapper incomeExpenditureMapper;

    public UniquenessValidationHandler(IncomeExpenditureMapper incomeExpenditureMapper) {
        this.incomeExpenditureMapper = incomeExpenditureMapper;
    }

    @Override
    public void setNext(ValidationHandler next) {
        this.next = next;
    }

    @Override
    public void validate(UpdateDoubleDTO dto) {
        if (dto.getId() == null) { // 仅新增需要校验唯一性
            long count = incomeExpenditureMapper.selectCount(new LambdaQueryWrapper<IncomeExpenditure>()
                    .eq(IncomeExpenditure::getCode, dto.getCode())
                    .eq(IncomeExpenditure::getYear, Integer.parseInt(dto.getYear()))
                    .eq(IncomeExpenditure::getDeleted, 0));
            if (count > 0) {
                throw new RuntimeException("code=" + dto.getCode() + ",year=" + dto.getYear() + "的数据已存在");
            }
        }
        if (next != null) {
            next.validate(dto);
        }
    }
}